/**
 * $Id$
 */
package com.cy.util;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author kaven
 * 
 */
public class StringUtils {

	public static String sqlnull(String source) {
		if (source == null) {
			return "";
		} else {
			return source;
		}
	}

	private static StringUtils classInstance = new StringUtils();

	public static final String EMPTY_STRING_ARRAY[] = new String[0];

	public static StringUtils getInstance() {
		return classInstance;
	}

	private StringUtils() {
	}

	public static String[] getStrAddress(String str) {
		String[] strAddress = str.split("<br>");
		return strAddress;

	}

	public static boolean isNumeric(String str) {
		if (str == null)
			return false;
		int sz = str.length();
		if (sz == 0)
			return false;
		for (int i = 0; i < sz; i++)
			if (!Character.isDigit(str.charAt(i)))
				return false;

		return true;
	}

	public static String filterText(String content) {
		content = content.replaceAll("\\[img\\]", "<img src=");

		content = content.replaceAll("\\[\\/img\\]", " />");

		content = content.replaceAll("\\[code\\]",
				"<table width=100% border=1 bgcolor=#99FFFF><tr><td><p>");
		content = content.replaceAll("\\[\\/code\\]", "</p></td></tr></table>");

		return content;
	}

	// 验证字符是否日期
	public static boolean isDate(String str, String format) {
		Date dp1;
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		sdf.setLenient(false);// 这个的功能是不把1996-13-3 转换�?1997-1-3
		try {
			dp1 = sdf.parse(str);

		} catch (Exception e) {
			return false;
		}
		return true;
	}

	public static boolean isEmpty(String str) {
		return str == null || str.length() == 0;
	}

	public static boolean isNotEmpty(String str) {
		return str != null && str.length() > 0;
	}

	public static String substring(String str, int start, int end) {
		if (str.length() <= end)
			end = str.length();
		String temp = str.substring(start, end);
		if (str.length() > temp.length())
			temp += "...";
		return temp;
	}

	public static int lastIndexOf(String str, char searchChar) {
		if (str == null || str.length() == 0)
			return -1;
		else
			return str.lastIndexOf(searchChar);
	}

	public static int lastIndexOf(String str, char searchChar, int startPos) {
		if (str == null || str.length() == 0)
			return -1;
		else
			return str.lastIndexOf(searchChar, startPos);
	}

	public static int lastIndexOf(String str, String searchStr) {
		if (str == null || searchStr == null)
			return -1;
		else
			return str.lastIndexOf(searchStr);
	}

	public static int lastIndexOf(String str, String searchStr, int startPos) {
		if (str == null || searchStr == null)
			return -1;
		else
			return str.lastIndexOf(searchStr, startPos);
	}

	public static String substring(String str, int start) {
		if (str == null)
			return null;
		if (start < 0)
			start = str.length() + start;
		if (start < 0)
			start = 0;
		if (start > str.length())
			return "";
		else
			return str.substring(start);
	}

	public static String[] split(String str) {
		return split(str, null, -1);
	}

	@SuppressWarnings("unchecked")
	public static String[] split(String str, char separatorChar) {
		if (str == null)
			return null;
		int len = str.length();
		if (len == 0)
			return EMPTY_STRING_ARRAY;
		List list = new ArrayList();
		int i = 0;
		int start = 0;
		boolean match = false;
		while (i < len)
			if (str.charAt(i) == separatorChar) {
				if (match) {
					list.add(str.substring(start, i));
					match = false;
				}
				start = ++i;
			} else {
				match = true;
				i++;
			}
		if (match)
			list.add(str.substring(start, i));
		return (String[]) list.toArray(new String[list.size()]);
	}

	public static String[] split(String str, String separatorChars) {
		return split(str, separatorChars, -1);
	}

	@SuppressWarnings("unchecked")
	public static String[] split(String str, String separatorChars, int max) {
		if (str == null)
			return null;
		int len = str.length();
		if (len == 0)
			return EMPTY_STRING_ARRAY;
		List list = new ArrayList();
		int sizePlus1 = 1;
		int i = 0;
		int start = 0;
		boolean match = false;
		if (separatorChars == null)
			while (i < len)
				if (Character.isWhitespace(str.charAt(i))) {
					if (match) {
						if (sizePlus1++ == max)
							i = len;
						list.add(str.substring(start, i));
						match = false;
					}
					start = ++i;
				} else {
					match = true;
					i++;
				}
		else if (separatorChars.length() == 1) {
			char sep = separatorChars.charAt(0);
			while (i < len)
				if (str.charAt(i) == sep) {
					if (match) {
						if (sizePlus1++ == max)
							i = len;
						list.add(str.substring(start, i));
						match = false;
					}
					start = ++i;
				} else {
					match = true;
					i++;
				}
		} else {
			while (i < len)
				if (separatorChars.indexOf(str.charAt(i)) >= 0) {
					if (match) {
						if (sizePlus1++ == max)
							i = len;
						list.add(str.substring(start, i));
						match = false;
					}
					start = ++i;
				} else {
					match = true;
					i++;
				}
		}
		if (match)
			list.add(str.substring(start, i));
		return (String[]) list.toArray(new String[list.size()]);
	}

	public static boolean arrayContains(String[] arr, String str) {
		if (str == null)
			return false;
		for (String s : arr) {
			if (s.equalsIgnoreCase(str))
				return true;
		}
		return false;
	}

	public static void sort(int[] data) {
		for (int i = 0; i < data.length; i++) {
			for (int j = data.length - 1; j > i; j--) {
				if (data[j] < data[j - 1]) {
					swap(data, j, j - 1);
				}
			}
		}
	}

	public static void sortList(List data) {
		for (int i = 0; i < data.size(); i++) {
			for (int j = data.size() - 1; j > i; j--) {
				@SuppressWarnings("unused")
				String sdfsd = ((Object[]) data.get(j))[1] + "";
				if (Double.parseDouble(((Object[]) data.get(j))[1] + "") < Double
						.parseDouble(((Object[]) data.get(j - 1))[1] + "")) {
					swapList(data, j, j - 1);
				}
				sdfsd = null;
			}
		}
	}

	public static void sortDescList(List data) {
		for (int i = 0; i < data.size(); i++) {
			for (int j = data.size() - 1; j > i; j--) {
				@SuppressWarnings("unused")
				String sdfsd = ((Object[]) data.get(j))[1] + "";
				if (Double.parseDouble(((Object[]) data.get(j))[1] + "") > Double
						.parseDouble(((Object[]) data.get(j - 1))[1] + "")) {
					swapList(data, j, j - 1);

				}
				sdfsd = null;
			}
		}

	}

	@SuppressWarnings("unchecked")
	private static void swapList(List data, int i, int j) {
		Object temp = data.get(i);
		data.set(i, data.get(j));
		data.set(j, temp);
		temp = null;
	}

	private static void swap(int[] data, int i, int j) {
		int temp = data[i];
		data[i] = data[j];
		data[j] = temp;
	}

	public static String formatIntToStr(int num, String pattern) {
		DecimalFormat df = new DecimalFormat(pattern);

		return df.format(num);
	}

	public static Long[] string2Long(String[] strs) {
		if (strs == null) {
			return new Long[0];
		}

		Long[] ls = new Long[strs.length];

		for (int i = 0; i < strs.length; i++) {
			ls[i] = Long.valueOf(strs[i]);
		}

		return ls;
	}

	public static String toChi(String input) {
		try {
			byte[] bytes = input.getBytes("ISO8859-1");

			return isValidUtf8(bytes, bytes.length) ? new String(bytes, "utf-8")
					: new String(bytes);
		} catch (Exception ex) {
		}

		return null;
	}

	public static boolean isValidUtf8(byte[] b, int aMaxCount) {
		int lLen = b.length;
		int lCharCount = 0;

		for (int i = 0; (i < lLen) && (lCharCount < aMaxCount); ++lCharCount) {
			byte lByte = b[i++]; // to fast operation, ++ now, ready for the
			// following for(;;)

			if (lByte >= 0) {
				continue; // >=0 is normal ascii
			}

			if ((lByte < (byte) 0xc0) || (lByte > (byte) 0xfd)) {
				return false;
			}

			int lCount = (lByte > (byte) 0xfc) ? 5 : ((lByte > (byte) 0xf8) ? 4
					: ((lByte > (byte) 0xf0) ? 3 : ((lByte > (byte) 0xe0) ? 2
							: 1)));

			if ((i + lCount) > lLen) {
				return false;
			}

			for (int j = 0; j < lCount; ++j, ++i)
				if (b[i] >= (byte) 0xc0) {
					return false;
				}
		}

		return true;
	}

	public static Date afterDate(String date, String pattern) {
		SimpleDateFormat fo = new SimpleDateFormat();

		if (pattern == null) {
			pattern = "yyyy-MM-dd HH:mm:ss";
		}
		fo.applyPattern(pattern);
		Date tempdate = null;
		try {
			tempdate = fo.parse(date);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return tempdate;
	}

	public static boolean between(Date startDate, Date endDate) {
		if (startDate.after(endDate))
			return false;

		return true;
	}

	public static Integer getStateNow() {
		Date d = new Date();
		SimpleDateFormat s = new SimpleDateFormat("yyyyMMdd");
		Integer i = Integer.parseInt(s.format(d));
		return i;
	}

	public static void main(String[] args) {
		System.out.println(getStateBeforeNow());
		System.out.println(isDate("2009-07-27", "yyyy-MM-dd"));
		System.out.println(getStateNow());
	}

	public static Integer getStateBeforeNow() {
		Date d = new Date();

		int day = d.getDate();
		if (day == 1) {
			d.setDate(31);
		} else {
			d.setDate(d.getDate() - 1);
		}
		SimpleDateFormat s = new SimpleDateFormat("yyyyMMdd");
		Integer i = Integer.parseInt(s.format(d));
		return i;
	}

	public static String convertToBr(String content) {
		if (StringUtils.isNotEmpty(content)) {
			content = content.replaceAll("\r\n", "<br />");
		}

		return content;
	}

	/*
	 * ���String originalStr ԭ4��str fillChar �����ֶ� fillStrLen �����str�ĳ���
	 */
	public static String fillString(String originalStr, String fillChar,
			int fillStrLen) {
		if (isEmpty(originalStr)) {
			originalStr = "";
		}
		if (originalStr.length() > fillStrLen) {
			return originalStr;
		}
		StringBuffer fillStr = new StringBuffer();
		for (int i = 0; i < fillStrLen - originalStr.length(); i++) {
			fillStr.append(fillChar);
		}
		return fillStr.toString() + originalStr;
	}

	/*
	 * �ж��Ƿ���Խ������stringֵת��ΪbigDecimal
	 */
	public static boolean checkBigDecimal(String targetString) {
		BigDecimal tmp = null;
		try {
			tmp = new BigDecimal(targetString);
		} catch (NumberFormatException e) {
		}
		if (tmp != null) {
			return true;
		}
		return false;
	}

	public static Object sqlnullLimit(String source, int limit) {
		String result = "";

		if (source == null) {
			result = "";
		} else {
			result = source;
		}

		if (result.length() > limit) {
			result = result.substring(0, limit);
		}

		return result;
	}

	
	/**
	 * �������ʼ��Ϸ���
	 * @param mail
	 * @return
	 */
	public static boolean checkEmail(String mail) {
		String regex = "\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*";
		Pattern p = Pattern.compile(regex);
		Matcher m = p.matcher(mail);
		return m.find();
	}
	
	/**
	 * ���N��A-Z�������
	 * @param str	��ɺ�����
	 * @param length ���nλ 
	 */
	public static void getRandomString(StringBuffer str,int length) {		
		for (int i = 0; i < length; i++) {
			int n = new Double(Math.random() * 26 + 65).intValue();
			str.append((char) n);
		}
	}
	
	/**
	 * ���N��0-9�������
	 * @param str	��ɺ�����
	 * @param length ���nλ 
	 */
	public static void getRandomNumString(StringBuffer str,int length) {		
		for (int i = 0; i < length; i++) {
			int n = new Double(Math.random() * 10).intValue();
			str.append(n);
		}
	}
	
	/**
	 * ���N��0-9A-Z�������
		 * @param str	��ɺ�����
	 * @param length ���nλ 
	 */
	private void createRandomAllString(StringBuffer str,int length){
		  String[] code = {"0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K"
		    ,"L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
		  Random rd = new Random(System.currentTimeMillis());
		  for (int i=1;i<=length;i++){			 
			  str.append((code[rd.nextInt(36)]));
		  }
	}

	/**
	 * 
	 *  Created on Dec 21, 2011 
	 * <p>Discription:[i�����]</p>
	 * @author:[�] [yanghuan]@homevv.com
	 * @update:[����YYYY-MM-DD] [���������]
	 * @return String
	 */
    public static String addTowStr(String str1, String str2)
    {
        if(isNumeric(str1) && isNumeric(str2))
        {
            return new BigDecimal(str1).add(new BigDecimal(str2)).toString();
        }
        return null;
    }
    
    public static List<String> pareseHtmlString(String str){
    	str=str.replaceAll("\"", "'");
		List<String> list = new ArrayList<String>();
		String pattern = "<img[^>]*?src=\'([^\']*||[^\"]*)\'[^>]*>";
		Matcher m = Pattern.compile(pattern).matcher(str);
		while (m.find()) {
			String s = m.group(1).substring(m.group(1).lastIndexOf("/") + 1);
			list.add(s);
		}
		return list;
	}
    
	public static String getVerifyCode(){
		UUID uuid = UUID.randomUUID();
		return uuid.toString();
	}
	
	public static ArrayList<String> removeDuplicate(ArrayList<String> arlList) {
		HashSet h = new HashSet(arlList);
		arlList.clear();
		arlList.addAll(h);
		return arlList;
	}

}
